package com.qy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qy.entity.Order;
import com.qy.mapper.OrderMapper;
import com.qy.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    
    private final OrderMapper orderMapper;
    
    @Override
    public Order createOrder(Order order) {
        try {
            // 生成唯一订单编号
            if (order.getId() == null || order.getId().isEmpty()) {
                order.setId(generateOrderId());
            }
            
            // 设置创建时间
            if (order.getCreateTime() == null) {
                order.setCreateTime(new Date());
            }

            order.setStatus("pending");
            
            // 保存订单
            orderMapper.insert(order);
            log.info("创建订单成功: {}", order.getId());
            return order;
        } catch (Exception e) {
            log.error("创建订单失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建订单失败", e);
        }
    }
    
    @Override
    public Order getOrderById(String orderId) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getId, orderId);
        return orderMapper.selectOne(wrapper);
    }
    
    @Override
    public List<Order> getOrdersByUserId(String userId) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId);
        return orderMapper.selectList(wrapper);
    }
    
    @Override
    public List<Order> getOrdersByStatus(String status) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getStatus, status);
        return orderMapper.selectList(wrapper);
    }
    
    @Override
    public List<Order> getOrdersByTimeRange(Date startTime, Date endTime) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(Order::getCreateTime, startTime, endTime);
        return orderMapper.selectList(wrapper);
    }
    
    @Override
    public boolean updateOrderStatus(String orderId, String status, String statusName) {
        try {
            Order order = new Order();
            order.setId(orderId);
            order.setStatus(status);
            order.setStatusName(statusName);
            
            // 根据状态更新相应时间
            if ("paid".equals(status)) {
                order.setPaymentTime(new Date());
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                order.setEffectiveTime(calendar.getTime());
            } else if ("active".equals(status)) {
                order.setEffectiveTime(new Date());
            }
            
            int result = orderMapper.updateById(order);
            log.info("更新订单状态成功: {}, 状态: {}", orderId, status);
            return result > 0;
        } catch (Exception e) {
            log.error("更新订单状态失败: {}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean payOrder(String orderId) {
        return updateOrderStatus(orderId, "paid", "已支付");
    }
    
    @Override
    public boolean cancelOrder(String orderId) {
        return updateOrderStatus(orderId, "canceled", "已取消");
    }
    
    @Override
    public List<Order> queryOrdersByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        
        // 构建动态查询条件
        if (params != null) {
            String orderId = (String) params.get("orderId");
            if (StringUtils.isNotBlank(orderId)) {
                wrapper.eq(Order::getId, orderId);
            }
            
            String userId = (String) params.get("userId");
            if (StringUtils.isNotBlank(userId)) {
                wrapper.eq(Order::getUserId, userId);
            }
            
            String status = (String) params.get("status");
            if (StringUtils.isNotBlank(status)) {
                wrapper.eq(Order::getStatus, status);
            }
            
            Date startDate = (Date) params.get("startDate");
            Date endDate = (Date) params.get("endDate");
            if (startDate != null && endDate != null) {
                wrapper.between(Order::getCreateTime, startDate, endDate);
            } else if (startDate != null) {
                wrapper.ge(Order::getCreateTime, startDate);
            } else if (endDate != null) {
                wrapper.le(Order::getCreateTime, endDate);
            }
        }
        
        return orderMapper.selectList(wrapper);
    }
    
    @Override
    public long getOrderCount() {
        return orderMapper.selectCount(null);
    }
    
    @Override
    public long getOrderCountByStatus(String status) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getStatus, status);
        return orderMapper.selectCount(wrapper);
    }
    
    /**
     * 生成订单编号
     */
    private String generateOrderId() {
        // 订单编号格式：ORD + 年月日时分秒 + 6位随机数
        String timestamp = String.format("%tY%<tm%<td%<tH%<tM%<tS", new Date());
        String random = String.format("%06d", (int) (Math.random() * 1000000));
        return "ORD" + timestamp + random;
    }
}
